<template>
    <div>
        <label v-if="label" class="my-2">{{ label }}</label>
        <slot></slot>
    </div>
</template>

<script>
import Schema from 'async-validator';
export default {
    inject: ['model', 'rules'],
    props: {
        prop: String,
        label: String,
    },
    data() {
        return {
            errorMessage: '',
        };
    },
    mounted() {
        this.$on('validate-input', (value) => {
            this.validate(value);
        });
    },
    methods: {
        validate(value) {
            // 校验描述
            const descriptor = {
                [this.prop]: this.rules[this.prop],
            };
            const children = this.$children;
            children[0].isValid = true;
            // 创建一个校验器
            // 需要安装校验器 npm i async-validator -S
            const validator = new Schema(descriptor);
            return validator.validate(
                { [this.prop]: value },
                (errors, fields) => {
                    if (errors) {
                        children[0].isValid = false;
                        this.errorMessage = errors[0].message;
                    }
                    return;
                }
            );
        },
    },
};
</script>
